require 'image_size'
require 'fileutils'
require 'digest/md5'
class GlobalController < ApplicationController
  layout "company",:except=>[:paidnotify]
  before_filter :check_authentication,:except=>[:paidnotify,:paidhandle]
  def setting
    @company = @cur_user.company
    @account_owner = @company.account_owner
    @size = session[:size]
    @paid_i = (@company.payments.size + 11).to_s
    @md5 = Digest::MD5
  end
  def payments
    @company = Company.find(params[:company][:id]) 
    @md5 = Digest::MD5
    @paid_i = (@company.payments.size + 11).to_s
    @plan = Plan.find(params[:plan_id].split("_").first)
    @month = params[:up_month]
  end
  def paidnotify
    @payment = Payment.new
    @payment.company_id = params[:c_order].to_i/100 
    @payment.amount     = params[:c_orderamount].to_i
    @payment.save
    @company = Company.find(@payment.company_id)
    @company.plan_id = params[:c_memo1].to_i
    @company.save
    render_text "<result>1</result><reURL>http://#{@company.url}.trikr.com/global/paidhandle</reURL>"
  end
  def paidhandle
    redirect_to '/global/setting'
  end
  def upload_logo
    path = "#{RAILS_ROOT}/public/files/logos/#{@cur_user.company.id}/"
    if not File.exist?( path )
      Dir.mkdir( path )
    end
    file = params[:file]
    file_type = ""
    file_type = file.original_filename.split(".").last.downcase if file !=""
    if  file_type.match("gif") or file_type.match("jpg") or file_type.match("jpeg") or file_type.match("png")
       File.open(path + "/tmp_logo.gif","wb") do |f|
         f.write file.read
	 f.close
       end
       file = File.new( path + "/tmp_logo.gif","r")
      #check image size
      @size =  ImageSize.new(file.read)
      if @size.width > 200 or @size.height > 200
        session[:size] = @size
        flash[:notice] = "Your logo [WIDTH*HEIGHT] is %s, wide than 200px"
        FileUtils.remove_file(path + '/tmp_logo.gif')
      else
        FileUtils.mv(path + 'tmp_logo.gif',path + 'logo.gif')
      end
    else
      flash[:notice] = "You uploaded an invalid file"
    end
    redirect_to '/global/setting'
  end
  def delete_logo
    path = "#{RAILS_ROOT}/public/files/logos/#{@cur_user.company.id}/logo.gif"
    File.delete path
    redirect_to '/global/setting'
  end
  def update_name
    @cur_user.company.name = params[:company][:name]
    @cur_user.company.save
    redirect_to '/global/setting'
  end
  def update_owner
    @cur_user.company.owner_id = params[:company][:owner_id]
    @cur_user.company.save
    redirect_to '/global/setting'
  end
  def update_plan
    @cur_user.company.plan_id = params[:company][:plan_id]
    @cur_user.company.save
    redirect_to '/global/setting'
  end
end
